package logic

import (
	"MyBlogv2/Servers/UserAction/internal/svc"
	UserAction "MyBlogv2/Servers/UserAction/userAction"
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/redisUtil"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type LikeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLikeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikeLogic {
	return &LikeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LikeLogic) Like(in *UserAction.UserActionRequest) (*UserAction.LikeResponse, error) {
	typeOfLike := int(in.Type)
	typeId := int(in.TypeId)
	userId := int(in.UserId)
	var dbCount int64
	models.Db.Model(new(models.Like)).Where("user_id = ? and type = ? and type_id = ?", userId, typeOfLike, typeId).Count(&dbCount)
	if dbCount > 0 {
		return &UserAction.LikeResponse{
			Code: int64(HttpCode.FAILURE.GetCode()),
		}, nil
	}
	var like models.Like
	like.UserId = userId
	like.Type = typeOfLike
	like.TypeId = typeId
	models.Db.Model(new(models.Like)).Create(&like)
	if typeOfLike == define.LIKE_TYPE_ARTICLE {
		redisUtil.AddLikeCount(typeId)
	}
	return &UserAction.LikeResponse{
		Code: int64(HttpCode.SUCCESS.GetCode()),
	}, nil
}
